ThreadManager = {}


function ThreadManager:initialize()
	self.threads = {}

end

function ThreadManager:nt( type )
	local iter = #ThreadManager.threads+1
	ThreadManager.threads[iter] = {}
	ThreadManager.threads[iter].id = iter
	ThreadManager.threads[iter].t = MOAICoroutine.new()
	local action = ThreadManager.threads[iter]
	if type == "map" then 
		action:setListener(MOAIAction.EVENT_STOP, 
			ThreadManager.map_thread_finished)
	elseif type == "main" then
		action:setListener(MOAIAction.EVENT_STOP,
			ThreadManager.main_thread_finished)
	
	else
		action:setListener(MOAIAction.EVENT_STOP,
			ThreadManager.thread_finished)
	end
	return ThreadManager.threads[iter]

end

function ThreadManager:cleanup()

	local threads = self.threads
	
	for i = #threads, 1, -1 do
	
		if threads[i]:isDone() then
		
			table.remove(threads, i)
		
		end
	
	end

end

function ThreadManager:update()

	self:cleanup()

end

function ThreadManager:thread_finished()

	

	--print("THREAD MANAGER thread finished")
end

function ThreadManager:main_thread_finished()
	
	--print("THREAD MANAGER main thread finished")
end

function ThreadManager:map_thread_finished()

	--print("THREAD MANAGER map thread finished")
end

function ThreadManager:thread_count()

	return #self.threads
end

function ThreadManager:get_thread( iter )

	return self.threads[iter]

end

function ThreadManager:funcify( action )
	local s =
	[[ local func = function() ]] .. action .. [[ end ]]
	
	return loadstring(s)

end

function ThreadManager:wait_thread ( iter )

	while self.threads[iter]:isBusy() do coroutine:yield() end

end

function ThreadManager:wait_multi ( funcs )

	for i = 1, #funcs do
	
		while funcs[i]:isBusy() do coroutine:yield() end
	end

end


function ThreadManager:wait( action )

	while action:isBusy() do coroutine:yield() end

end


return ThreadManager